package mgox

import (
	"context"
	"errors"
	"strings"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func MongoDatabase(ctx context.Context, uri, db string) (*mongo.Database, error) {
	c, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		return nil, err
	}
	err = c.Ping(context.Background(), nil)
	if err != nil {
		return nil, err
	}
	return c.Database(db), nil
}

// IsErrDuplicateKey 是否为重复Key错误
func IsErrDuplicateKey(err error) bool {
	if err == nil {
		return false
	}
	return strings.Contains(err.Error(), "write exception: write errors: [E11000 duplicate key error collection")
}

func CheckErrNoDocuments(err error) error {
	if err == nil {
		return nil
	}
	if errors.Is(err, mongo.ErrNoDocuments) {
		return errors.New("文档不存在")
	}
	return err
}
